package com.xy6.model.service.monitor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.xy6.model.api.bean.MyStatusWrapper;
import com.xy6.model.api.enums.MyStatus;

/**
 * @author zhang
 * @since 
 */
public class MyTaskMonitor {
	
	/**
	 * 保存task的运行状态，多线程共享
	 * <jobid,[<task01,create>]>
	 */
	private static Map<String, Map<String, MyStatusWrapper>> tasks = new ConcurrentHashMap<>(100);

	public static Map<String, MyStatusWrapper> getJobStatus(String jobId){
		if(!tasks.containsKey(jobId)){
			return new HashMap<String, MyStatusWrapper>(0);
		}
		return tasks.get(jobId);
	}
	
	/**
	 * 保存一个task的状态
	 * 
	 * @param jobId
	 * @param taskId
	 * @param status
	 */
	public static void put(String jobId, String taskId, MyStatus status){
		MyStatusWrapper newStatus = new MyStatusWrapper(status, new Date());
		if(tasks.containsKey(jobId)){
			tasks.get(jobId).put(taskId, newStatus);
		} else {
			ConcurrentHashMap<String, MyStatusWrapper> subMap = new ConcurrentHashMap<>(5); 
			subMap.put(taskId, newStatus);
			tasks.put(jobId, subMap);
		}
	}
	
	/**
	 * 判断任务是否结束
	 * 
	 * @param jobId
	 * @param taskId
	 * @return
	 */
	public static boolean isTaskEnd(String jobId, String taskId){
		return isTaskBeStatus(jobId, taskId, MyStatus.END);
	}
	
	/**
	 * 判断任务是否结束
	 * 
	 * @param jobId
	 * @param taskId
	 * @return
	 */
	public static boolean isTaskBegin(String jobId, String taskId){
		return isTaskBeStatus(jobId, taskId, MyStatus.BEGIN);
	}
	
	/**
	 * 判断任务是否为某一状态
	 * 
	 * @param jobId
	 * @param taskId
	 * @return
	 */
	private static boolean isTaskBeStatus(String jobId, String taskId, MyStatus status){
		if(!tasks.containsKey(jobId)){
			return false;
		}
		if(!tasks.get(jobId).containsKey(taskId)){
			return false;
		}
		if(!status.getName().equals(tasks.get(jobId).get(taskId).getName())){
			return false;
		}
		return true;
	}
	
}
